'''
Created on 28-11-2010

@author: mwi
'''

from threading import Thread
import time

from sniffylib.core import services

class ServiceThread(Thread):
    
    def __init__(self, cb, delay=None):
        Thread.__init__(self)
        self.daemon = True
        self.cb = cb
        self.running = False
        self.delay = delay
        
    def run(self):
        self.running = True
        while self.running:
            self.cb()
            if self.delay is not None:
                time.sleep(self.delay)
         
    def stop(self):
        self.running = False   
    

class BgService(services.BaseService):
    
    def __init__(self, cb, delay=None):
        services.BaseService.__init__(self)        
        self.cb = cb
        self.delay = delay
        self.service_thread = None
    
    def start_service(self):
        self.service_thread = ServiceThread(self.cb, self.delay)
        self.service_thread.start()
        
    def stop_service(self):
        if self.service_thread:
            self.service_thread.stop()
